from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
from apps.areas.models import Area
# 只负责查询城市表数据
from utils.response_code import RETCODE
from django.core.cache import cache


class AreasView(View):
    def get(self, request):
        # 接收参数
        area_id = request.GET.get('area_id')
        if not area_id:
            # 给选取地址增加缓存
            province_list = cache.get('province_list')
            if not province_list:
                provinces = Area.objects.filter(parent_id__isnull=True)
                province_list = []
                for pro in provinces:
                    province_list.append({
                        "id":pro.id,
                        "name":pro.name,
                    })
                    # 需要存一下
                cache.set('province_list', province_list, 3600)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:
            sub_data = cache.get('sub_data_%s' %area_id)
            if not sub_data:

                parent_model = Area.objects.get(id=area_id)
                cities = parent_model.subs.all()
                subs_list = []
                for city in cities:
                    subs_list.append({
                        "id":city.id,
                        "name":city.name,
                    })
                sub_data = {
                    'id':parent_model.id,
                    "name":parent_model.name,
                    "subs": subs_list,
                }
                cache.set('sub_data_%s' %area_id,sub_data, 3600)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})